package com.yonyou.gmmc.service.pointactivity.controller;

import com.yonyou.gmmc.common.sms.SmsHttpClient;
import com.yonyou.gmmc.service.pointactivity.constant.PointActivityConstant;
import com.yonyou.gmmc.service.pointactivity.dto.ResultBillDate;
import com.yonyou.gmmc.service.pointactivity.model.*;
import com.yonyou.gmmc.service.pointactivity.service.NotReturnFactoryService;
import com.yonyou.gmmc.service.pointactivity.service.ReservationService;
import com.yonyou.gmmc.service.pointactivity.service.TmWinningAttributeService;
import com.yonyou.gmmc.service.pointactivity.service.TtWinnerRecordService;
import com.yonyou.gmmc.service.pointactivity.util.DateUtils;
import com.yonyou.gmmc.service.pointactivity.util.JsonUtilTemp;
import io.swagger.annotations.Api;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.marketing.common.dms.http.HttpCommonUtil;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 五周年购车回赠活动
 */
@RestController
@RequestMapping(value = PointActivityConstant.BASE_PATH + "/" + PointActivityConstant.VERSION)
@Api("五周年购车回赠活动")
public class FiveYearFeedBackController {
    private Logger logger = Logger.getLogger(FiveYearFeedBackController.class);
    @Autowired
    private TmWinningAttributeService tmWinningAttributeService;
    @Autowired
    private TtWinnerRecordService ttWinnerRecordService;
    @Autowired
    private NotReturnFactoryService notReturnFactoryService;
    // 注入省份查询及奖券初始化业务层
    @Autowired
    private ReservationService reservationService;
    // 活动类型
    private Integer ACTIVITY_TYPE = 3;
    // 操作人
    private Long OPERATION_BY = 111111111L;
    
	@Value("${DCMS-url}")
	private String dcmsUrl;
	@Value("${SMS-pass}")
	private String smsPass;
	@Value("${SMS-key}")
	private String smsKey;
	@Value("${SMS_CDKEY}")
	private String SMS_CDKEY;
	@Value("${SMS_PASS}")
	private String SMS_PASS;
	@Value("${SMS_BASEURL}")
	private String SMS_BASEURL;
    
    /**
     * 这个方法会在当前这个类(Controller)任何一个方法调用之前调用一次
     *
     * @param req
     */
    @ModelAttribute
    public void recordVisit(HttpServletRequest req) {
        String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
//        openId = null == openId ? "oXrcfuGUU-0hRB1GnYNtjl-PvcsM" : openId;
        try {

            if (com.yonyou.gmmc.service.pointactivity.util.StringUtils.isNull(openId))
                throw new Exception("openId为空.!");

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("openId", openId);
            param.put("activityType", ACTIVITY_TYPE);
//            //判断是否获取到用户所在省份地址信息
            if(req.getParameter("province")==null || "".equals(req.getParameter("province"))){
                //当省份为空时，查询用户所购车辆所在地省份
                String province=reservationService.getCarAndProvince(openId);
                param.put("province", province);
            }else {
                param.put("province", req.getParameter("province"));
            }
            param.put("createBy", OPERATION_BY);
            param.put("updateBy", OPERATION_BY);

            ttWinnerRecordService.recordVisit(param);
        } catch (Exception e) {
            logger.info("五周年购车回赠活动-记录用户访问次数.获取到openId:" + openId + ",访问记录异常.");
        }
    }

    @SuppressWarnings("unused")
	public synchronized Map<String, Object> returnLottery(TmWinningAttribute tmWinningAttribute, String openId, String vin) {
		String nowdate = DateUtil.getNowDate();
		Map<String, Object> recordMap = new HashMap<String, Object>();
		Integer firstWinningcount = null;// 每天剩余的一等奖
		Integer firstWinningChooseIndex = null;// = null;//当天第几个抽奖的人必中一等奖
		Integer firstWinningPoint = null;// 一等奖中奖积分
		Integer secondWinningcount = null;// 每天剩余的二等奖
		Integer secondWinningChooseIndex1 = null;// 当天第几个抽奖的人必中二等奖
		Integer secondWinningChooseIndex2 = null;// 当天第几个抽奖的人必中二等奖
		Integer secondWinningPoint = null;// 当二等奖中奖积分
		Integer thirdWinningcount = null;// 每天剩余的三等奖
		Integer prizeRecord = 0;// 当天抽奖数
		Integer probability = null;// 概率
		firstWinningcount = tmWinningAttribute.getFirstWinningcount();
		firstWinningChooseIndex = tmWinningAttribute.getFirstWinningChooseIndex();
		firstWinningPoint = tmWinningAttribute.getFirstWinningPoint();
		secondWinningcount = tmWinningAttribute.getSecondWinningcount();
		secondWinningChooseIndex1 = tmWinningAttribute.getSecondWinningChooseIndex1();
		secondWinningChooseIndex2 = tmWinningAttribute.getSecondWinningChooseIndex2();
		secondWinningPoint = tmWinningAttribute.getSecondWinningPoint();
		thirdWinningcount = tmWinningAttribute.getWinningcount();
		probability = tmWinningAttribute.getProbability();
		List<Map<String, Object>> ttWinnerRecords = ttWinnerRecordService.queryWinnerAttribute(nowdate);

		// 计算剩余的一等奖,二等奖,三等奖
		if (ttWinnerRecords != null && ttWinnerRecords.size() > 0) {
			prizeRecord = ttWinnerRecords.size() + 1;// 当天抽奖指针数
			Integer firstgetPrize = 0;
			Integer secondgetPrize = 0;
			Integer thirdgetPrize = 0;
			for (Map<String, Object> winnerRecord : ttWinnerRecords) {
				Object obj = winnerRecord.get("PRIZELEVEL");
				if (obj != null) {
					String prizelevel = String.valueOf(winnerRecord.get("PRIZELEVEL"));
					if (Integer.valueOf(prizelevel) == PointActivityConstant.PRIZE_LEVEL_ONE) {
						firstgetPrize++;
					} else if (Integer.valueOf(prizelevel) == PointActivityConstant.PRIZE_LEVEL_TWO) {
						secondgetPrize++;
					} else if (Integer.valueOf(prizelevel) == PointActivityConstant.PRIZE_LEVEL_THREE) {
						thirdgetPrize++;
					}
				}
			}
			firstWinningcount = firstWinningcount - firstgetPrize;
			secondWinningcount = secondWinningcount - secondgetPrize;
			thirdWinningcount = thirdWinningcount - thirdgetPrize;

		}

		// 中一等奖
		if (firstWinningcount > 0 && prizeRecord == firstWinningChooseIndex) {
			recordMap.put("prize", PointActivityConstant.PRIZE_LEVEL_ONE);
			recordMap.put("prizepoint", PointActivityConstant.PRIZE_LEVEL_ONE_POINT);
		} else {
			if (secondWinningcount > 0 && (prizeRecord == secondWinningChooseIndex1 || prizeRecord == secondWinningChooseIndex2)) {
				// 中二等奖
				recordMap.put("prize", PointActivityConstant.PRIZE_LEVEL_TWO);
				recordMap.put("prizepoint", PointActivityConstant.PRIZE_LEVEL_TWO_POINT);
			} else {

				// 计算三等奖,
				Boolean flag = false;

				if (thirdWinningcount > 0) {
					if (probability != null) {
						flag = returnHasPrize(Double.valueOf(probability));// 是否中奖
					}

				}
				if (flag) {
					recordMap.put("prize", PointActivityConstant.PRIZE_LEVEL_THREE);
					recordMap.put("prizepoint", PointActivityConstant.PRIZE_LEVEL_THREE_POINT);
				}
			}
		}

		// 纪录抽奖信息
		TtWinnerRecord ttWinnerRecord = new TtWinnerRecord();
		ttWinnerRecord.setCreate_date(nowdate);
		ttWinnerRecord.setVin(vin);
		if (recordMap.containsKey("prize")) {
			ttWinnerRecord.setIfprize(PointActivityConstant.HAS_PRIZE);
			ttWinnerRecord.setPrizelevel(String.valueOf(recordMap.get("prize")));
		} else {
			ttWinnerRecord.setIfprize(PointActivityConstant.NOT_PRIZE);
		}
		if (StringUtils.isEmpty(ttWinnerRecord.getPrizelevel())) {
			ttWinnerRecord.setPrizelevel("");
		}
		if (StringUtils.isEmpty(ttWinnerRecord.getVin())) {
			ttWinnerRecord.setVin("");
		}
		ttWinnerRecord.setCreate_by("111111111");
		ttWinnerRecord.setUpdate_by("111111111");
		ttWinnerRecord.setOpenid(openId);
		ttWinnerRecord.setUpdate_date(nowdate);

		try {
			logger.info("五周年活动开始发送积分推送消息开始......");
			int count = ttWinnerRecordService.insertWinnerRecord(ttWinnerRecord, recordMap, openId);
			logger.info("五周年活动开始发送积分推送消息结束.....响应行:" + count);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}

		recordMap.put("hasprize", ttWinnerRecord.getIfprize());// 0未中奖 1中奖
		recordMap.put("prizelevel", ttWinnerRecord.getPrizelevel());

		return recordMap;
	}
    @RequestMapping(value="/lotteryReport")
    public void lotteryReport(HttpServletRequest request, HttpServletResponse response){
        List<PrizeCountBo> prizeCountBos =   ttWinnerRecordService.queryRecordReport();
        JsonUtilTemp.returnJson(prizeCountBos,response);

    }




    /**
     * 页面刚进来查询到以前的留资信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("queryTmkeep")
	public void queryTmkeep(HttpServletRequest request, HttpServletResponse response) {
		String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
//		 String openId = "oXrcfuC1R4wosEPeJOHR7BPqaAOo";
		try {
			TmKeep tmKeep = ttWinnerRecordService.queryTmkeep(openId);
			if (tmKeep != null) {
				JsonUtilTemp.returnJson(tmKeep, response);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			JsonUtilTemp.returnExceptionJson(response, e.getMessage());
		}

	}


    /**
     * 查询当前用户验证码剩余秒数
     * @param request
     * @return
     */
    @RequestMapping("queryMsgSencond")
	public @ResponseBody Map<String, Object> queryMsgSencond(HttpServletRequest request, HttpServletResponse response) {
		String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
		// String openId = "oXrcfuGUU-0hRB1GnYNtjl-PvcsM";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long senconds = null;
		try {
			TmFiveYearFeedMsg tmFiveYearFeedMsg = ttWinnerRecordService.queryMsgSencond(openId);
			// 得到创建时间与当前时间算出相隔秒数
			if (tmFiveYearFeedMsg != null && tmFiveYearFeedMsg.getCreatDate() != null) {
				Date nowdate = DateUtils.getCurrentDateTime();
				Date msgdate = tmFiveYearFeedMsg.getCreatDate();
				senconds = (nowdate.getTime() - msgdate.getTime()) / 1000;
				// resultMap.put("msgnum",tmFiveYearFeedMsg.getMsgnum());
				resultMap.put("msgnum", tmFiveYearFeedMsg.getMsgnum());
				resultMap.put("senconds", senconds);
				resultMap.put("msgphone", tmFiveYearFeedMsg.getMsgphone());
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取验证码有效时间异常:" + e.getMessage());
		}

		return resultMap;
	}



    /**
     * 发送短信返回验证码
     * @param request
     * @param response
     */
    @RequestMapping(value="/sendMsg")
	public @ResponseBody Map<String, Object> sendMsg(HttpServletRequest request, HttpServletResponse response, String phone) {
		String returnstatus = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
		// String openId = "oXrcfuGUU-0hRB1GnYNtjl-PvcsM";
		Long senconds = null;
		try {
			if (StringUtils.isEmpty(openId)) {
				throw new Exception("openid不能为空");
			}
			// 验证手机验证码是否超过60秒
			TmFiveYearFeedMsg existtmFiveYearFeedMsg = ttWinnerRecordService.queryMsgSencond(openId);
			// 得到创建时间与当前时间算出相隔秒数
			if (existtmFiveYearFeedMsg != null && existtmFiveYearFeedMsg.getCreatDate() != null) {
				Date nowdate = DateUtils.getCurrentDateTime();
				Date msgdate = existtmFiveYearFeedMsg.getCreatDate();
				senconds = (nowdate.getTime() - msgdate.getTime()) / 1000;
				if (senconds <= 60) {
					resultMap.put("returnstatus", "发送短信频繁,请稍后再试");
					return resultMap;
				}
			}

			int msgnum;// 定义两变量

			Random ne = new Random();// 实例化一个random的对象ne
			msgnum = ne.nextInt(9999 - 1000 + 1) + 1000;// 为变量赋随机值1000-9999
			String retuncode = SmsHttpClient.sendSms(phone, "您的验证码为：" + msgnum + "(1分钟内有效)", smsPass, smsKey,SMS_CDKEY, SMS_PASS, SMS_BASEURL);
			logger.info("五周年发送短信返回码:" + retuncode + " 手机:" + phone);
			if (!StringUtils.isEmpty(retuncode) && "0".equals(retuncode)) {
				returnstatus = "发送短信成功";
				// 纪录到短信表
				TmFiveYearFeedMsg tmFiveYearFeedMsg = new TmFiveYearFeedMsg();
				tmFiveYearFeedMsg.setMsgnum(String.valueOf(msgnum));
				tmFiveYearFeedMsg.setMsgphone(phone);
				tmFiveYearFeedMsg.setOpenid(openId);
				ttWinnerRecordService.saveYearFeedMsg(tmFiveYearFeedMsg);
			} else {
				returnstatus = "发送短信失败，请稍后再试";
			}

			resultMap.put("returnCode", retuncode);
			resultMap.put("returnstatus", returnstatus);
			resultMap.put("msgnum", msgnum);

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("returnstatus", "发送短信异常");
			logger.error("五周年发送短信失败" + e.getMessage());
		}
		return resultMap;

	}

    /**
     * 抽奖
     * @param request
     * @return
     */
    @RequestMapping(value="/startLottery")
	public @ResponseBody Map<String, Object> startLottery(HttpServletRequest request, HttpServletResponse response, String openid) {
		// 拿到openid
		String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
		// String openId = "oXrcfuC1R4wosEPeJOHR7BPqaAOo";

		Map<String, Object> resultMap = new HashMap<>();// 结果集

		try {
			if (com.yonyou.gmmc.service.pointactivity.util.StringUtils.isNull(openId))
				throw new Exception("openId为空.!");
			Integer openidtype = notReturnFactoryService.judgeOpenIdType(openId);
			// 只有车主可以参加活动
			if (openidtype != PointActivityConstant.USER_TYPE_3.intValue()) {
				resultMap.put("errorMs", "未进行车主认证，请在个人中心完成车主认证");
				return resultMap;
			}

			// 查询车架号
			String vin = ttWinnerRecordService.queryVIN(openId);
			// 根据车架号查询是否抽奖过,抽过则返回相应信息
			if (StringUtils.isEmpty(vin) || StringUtils.isEmpty(openId)) {
				resultMap.put("errorMs", "后台系统未能匹配车主车架号与发动机号");
				return resultMap;
			} else {

				Map<String, Object> param = new HashMap<String, Object>();
				param.put("vin", vin);
				param.put("openid", openId);

				int count = ttWinnerRecordService.queryRecordByVIN(param);
				if (count > 0) {
					resultMap.put("errorMs", "抱歉,您的抽奖次数已用完,谢谢参与");
					return resultMap;
				}
			}

			List<ResultBillDate> result = null;
			Map<String, Object> paraminfo = new HashMap<>();
			paraminfo.put("vin", vin);
			result = HttpCommonUtil.getOwnerInfo(paraminfo, "IC011", PointActivityConstant.CARINFO_URL.replaceAll("dcmshost", dcmsUrl), ResultBillDate.class);
			if (null == result) {
				resultMap.put("errorMs", "抱歉,你所购买的车辆不在活动日期范围内");
				return resultMap; 
			}
			logger.info("五周年抽奖活动 To DCMS Url:" + PointActivityConstant.CARINFO_URL.replaceAll("dcmshost", dcmsUrl));
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// String lotterydate = sdf.format(result.get(0).getBillDate());
			Date lotterydate = result.get(0).getBillDate();

			logger.info("车辆开票时间" + lotterydate);

			String startdate = ttWinnerRecordService.queryDiffDateStart();
			String enddate = ttWinnerRecordService.queryDiffDateEnd();
			logger.info("车辆设置的开始时间" + startdate);
			logger.info("车辆设置的结束时间" + enddate);
			if(lotterydate==null){
				resultMap.put("errorMs", "抱歉,您购买的车辆不在我们活动日期范围内");
				return resultMap;
			}

			if (!StringUtils.isEmpty(startdate) && !StringUtils.isEmpty(enddate) && lotterydate != null) {
				if (DateUtil.beforDate(lotterydate, DateUtil.dataFormat(startdate)) || DateUtil.beforDate(DateUtil.dataFormat(enddate), lotterydate)) {
					resultMap.put("errorMs", "抱歉,你购买车辆的日期不在活动开票日期内");
					return resultMap;
				}
			}

			// 查询当天中奖纪录
			String nowdate = DateUtil.getNowDate();
			List<TmWinningAttribute> tmWinningAttributeList = tmWinningAttributeService.queryWinnerAttribute(nowdate);

			if (resultMap.containsKey("errorMs") && resultMap.get("errorMs") != null) {
				return resultMap;
			}

			if (tmWinningAttributeList != null && tmWinningAttributeList.size() > 0) {
				TmWinningAttribute tmWinningAttribute = tmWinningAttributeList.get(0);

				resultMap = returnLottery(tmWinningAttribute, openId, vin);
				// //抽奖并发控制
				// ReentrantLock myLock = new ReentrantLock();
				// myLock.lock();
				// try{
				// resultMap = returnLottery(tmWinningAttribute,openId,vin);
				// }catch (Exception e){
				// e.printStackTrace();
				// logger.error(e.getMessage());
				// resultMap.put("errorMs",e.getMessage());
				// }finally {
				//
				// myLock.unlock();
				// }

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("五周年活动错误信息" + e.getMessage());
			resultMap.put("errorMs", e.getMessage());
		}
		return resultMap;
	}

    /**
     * 根据概率随机得到是否中奖
     * @param probability
     * @return
     */
    public boolean returnHasPrize(double probability){
        Random random = new Random();
        int nextval = random.nextInt(100);
        return nextval<=probability?true:false;
    }
	@RequestMapping("queryTmKeepCountByDate")
	public @ResponseBody Map<String, Object> queryTmKeepCountByDate(HttpServletRequest request){
		Map<String,Object> resultMap = new HashedMap();
		try{

			List<TmKeepCountVo> tmKeepCountVos = ttWinnerRecordService.queryTmKeepCountByDate();
			StringBuffer resultmsg = new StringBuffer();
			if(tmKeepCountVos!=null&&tmKeepCountVos.size()>0){
				for(TmKeepCountVo tmKeepCountVo:tmKeepCountVos){
					resultmsg.append(tmKeepCountVo.getRegionName()+":"+tmKeepCountVo.getProviceName()+" 数量:"+tmKeepCountVo.getQuerycount()+"\n");
				}
			}
			resultMap.put("resultmsg",resultmsg);
		}catch (Exception e){
			e.printStackTrace();
			resultMap.put("resultmsg","获取数据异常"+e.getMessage());
			logger.info("获取留资纪录统计失败"+e.getMessage());
		}

		return resultMap;
	}

}
